<template>
  <div class="box">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="账号登录" name="first">
        <div class="slot">
          <el-input class="account" placeholder="请输入账号" prefix-icon="el-icon-user" v-model="accountNumber"
            :clearable="true">
          </el-input>
          <el-input class="pswd" placeholder="请输入密码" prefix-icon="el-icon-lock" v-model="pswd" :show-password="true"
            :clearable="true">
          </el-input>
          <!-- <div>
            <span class="login">验证：</span>
            <input style="width: 100px" type="text" placeholder="请输入验证码" class="input-val" v-model.trim="yanzhen"
              @keyup.enter="login_enter" />
            <canvas id="canvas" width="130px" height="33px" @click="handleCanvas"> </canvas>
          </div> -->

          <div class="yanZhenBox">
            <el-input type="text" placeholder="请输入验证码" maxlength="4" class="input-val" v-model.trim="yanzhen"
              @keyup.enter.native="Logging('账号登录')">
              <div slot="prefix" class="prefixIcon">
                <i class="iconfont icon-yanzhengma"></i>
              </div>
              <div slot="suffix" class="canvasBox">
                <canvas id="canvas" @click="handleCanvas"> </canvas>
              </div>
            </el-input>
          </div>

          <div class="control">
            <!-- <el-checkbox class="remember" v-model="checked" @change="isRemember()">记住账号</el-checkbox> -->
            <div></div>
            <a class="forget" href="javascript:void(0);">忘记密码?</a>
          </div>
          <button class="loginBtn" @click="Logging('账号登录')">登录</button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="验证码登录" name="second">
        <div class="slot">
          <el-input class="phoneInput" placeholder="请输入手机号" prefix-icon="el-icon-mobile-phone" v-model="phone"
            :clearable="true">
          </el-input>
          <el-input class="VerificationCode" placeholder="请输入验证码" v-model="verifyCode"
            @keyup.enter.native="Logging('验证码登录')">
            <i slot="prefix" class="iconfont icon-yanzhengma"></i>
            <span v-show="showGetCode" class="getCode" slot="suffix" @click="getVerificationCode()">获取验证码</span>
            <span class="timing" v-show="!showGetCode" slot="suffix">重新发送({{ count }})</span>
          </el-input>
          <el-checkbox class="remember" v-model="checked" @change="isRemember()">记住账号</el-checkbox>
          <button class="loginBtn" style="margin-top: 47px" @click="Logging('验证码登录')">
            登录
          </button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import httpApi from "@/http";
import store from "@/store/index";
export default {
  data() {
    return {
      activeName: "first",
      accountNumber: "",
      pswd: "",
      checked: false, //是否记住账号
      phone: "",
      verifyCode: "", //验证码
      timing: null,
      showGetCode: true,
      count: "", //验证码计时

      yanzhen: "", //输入框双向绑定的值
      true_code: "", //保存正确的验证码
      //比如下面是4个验证码，可以是[1,2,3,4]及以下，但是不能是[1，2，3，4，5]， 因为5无法被替换
      seconds: "",
      loading: false,
      value: '',
      key: ''
    };
  },
  methods: {
    smallLetter(yanzhen) {
      var str = yanzhen.split("");
      for (var i = 0; i < str.length; i++) {
        if (/^[A-Z]$/.test(str[i])) {
          str[i] = str[i].toLowerCase();
        }
      }

      this.yanzhen = str.join("");
      console.log(this.yanzhen)
    },
    smallLetter1(yanzhen) {
      var str = yanzhen.split("");
      for (var i = 0; i < str.length; i++) {
        if (/^[A-Z]$/.test(str[i])) {
          str[i] = str[i].toLowerCase();
        }
      }

      this.true_code = str.join("");
      console.log(this.true_code)
    },
    Logging(type) {


      if (type == "账号登录") {
        //console.log(this.loading)

        //4位验证码校验
        // this.smallLetter(this.yanzhen); //全部转为小写字母
        // this.smallLetter1(this.true_code); //全部转为小写字母
        // ////console.log('正确验证', this.true_code);
        if (this.yanzhen != this.true_code) {
          this.$message.error("验证码错误");
          this.handleCanvas();
          return;
        } else if (this.loading == true) {
          this.$message.warning('请勿频繁点击,正在登录中')
          return
        }


        this.loading = true
        ////console.log('点击了一次登录');
        let pswd = this.Rsa.encrypt(this.pswd)
        let params = {
          username: this.accountNumber,
          password: pswd,
          captchaVo: {
            value: this.yanzhen,
            key: this.key,
          },
          type: "0"
        };
        httpApi.loginApi.loginuser(params).then((res) => {
          ////console.log("登录结果", res);
          ////console.log(res.data.code);
          if (res.data.code == 200 && this.checked) {
            //code200 且 勾选记住账号 存local
            this.$store.commit("saveToken", {
              token: res.data.data.access_token,
              checked: this.checked,
            });

            ////console.log(res);
            ////console.log("token", store.state.token,);
            this.$message({
              message: "登录成功",
              type: "success",
            });
            params.checked = this.checked;
            localStorage.setItem("saveUser", JSON.stringify(params));
            ////console.log(this.$router);
            this.$router.push("/home/index");
          } else if (res.data.code == 200 && !this.checked) {
            //code200 且 未勾选记住账号  存session
            this.$store.commit("saveToken", {
              token: res.data.data.access_token,
              checked: !this.checked,
            });
            ////console.log(res);
            ////console.log("token", store.state.token);
            this.$message({
              message: "登录成功",
              type: "success",
            });
            ////console.log(this.$router);
            localStorage.removeItem("saveUser");
            this.$router.push("/home/index");
          }
          this.loading = false
          this.handleCanvas()

        });
      } else if (type == "验证码登录") {
        if (this.loading == true) {
          this.$message.warning('请勿频繁点击,正在登录中')
          return
        }
        this.loading = true

        let params = {
          username: this.phone,
          code: this.verifyCode,
          type: "1"
        };


        httpApi.loginApi.loginuser(params).then((res) => {
          ////console.log("登录结果", res);
          ////console.log(res.data.code);
          if (res.data.code == 200 && this.checked) {
            //code200 且 勾选记住账号 存local
            this.$store.commit("saveToken", {
              token: res.data.data.access_token,
              checked: this.checked,
            });

            ////console.log(res);
            ////console.log("token", store.state.token,);
            this.$message({
              message: "登录成功",
              type: "success",
            });
            ////console.log(this.$router);
            this.$router.push("/home/index");
          } else if (res.data.code == 200 && !this.checked) {
            //code200 且 未勾选记住账号  存session
            this.$store.commit("saveToken", {
              token: res.data.data.access_token,
              checked: !this.checked,
            });

            ////console.log(res);
            ////console.log("token", store.state.token);
            this.$message({
              message: "登录成功",
              type: "success",
            });
            ////console.log(this.$router);
            this.$router.push("/home/index");
          } else if (res.data.code == 500) {
            this.$message({
              message: res.data.msg,
              type: "error",
            });
          }
          this.loading = false

        });
      }


    },
    handleClick(tab, event) {
      // //console.log(tab, event);
    },
    isRemember() { },
    // 验证码 发送计数
    getVerificationCode() {

      if (this.phone == '') {
        this.$message.error('手机号不能为空')
        return
      } else if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        this.$message.error('手机号格式不正确')
        return
      }
      // let endTime=new Date().getTime()+60000  //获取未来60秒后的 日期时间

      // sessionStorage.setItem('endTime',endTime)

      this.showGetCode = false;
      const TIME_COUNT = 60; //倒计时初始值60秒
      if (!this.timing) {
        this.count = TIME_COUNT;
        this.timing = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {

            this.count--;
            this.seconds = this.count
            //console.log(this.seconds);
          } else {
            this.showGetCode = true;
            clearInterval(this.timing);
            this.timing = null;
          }
        }, 1000);
      }
      let params = {
        phone: this.phone,
        port: "SUPPLIER_LOGIN",

      }
      httpApi.loginApi.getAuditCode(params).then(res => {
        if (res.data.code == 200) {
          this.$message.success('获取验证码成功')
        }

      })
    },


    async Huoqucode() {
      let res = await httpApi.loginApi.getCaptcha()
      this.value = res.data.data.value
      this.key = res.data.data.key
      console.log(res)
      this.draw()

    },
    //20211115 新增验证码功能
    //显示验证码区域内容信息
    async draw() {
      var show_num = []
      var canvas_width = document.querySelector("#canvas").clientWidth;
      var canvas_height = document.querySelector("#canvas").clientHeight;
      var canvas = document.getElementById("canvas"); //获取到canvas
      var context = canvas.getContext("2d"); //获取到canvas画图
      canvas.width = canvas_width;
      canvas.height = canvas_height;
      var sCode =
        "a,b,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
      var aCode = sCode.split(",");
      var aLength = aCode.length; //获取到数组的长度

      //4个验证码数
      for (var i = 0; i <= this.value.length; i++) {
        var j = Math.floor(Math.random() * aLength); //获取到随机的索引值
        var deg = (Math.random() * 30 * Math.PI) / 180; //产生0~30之间的随机弧度
        var txt = this.value[i]; //得到随机的一个内容

        // show_num[i] = txt.toLowerCase(); // 依次把取得的内容放到数组里面
        var x = 10 + i * 20; //文字在canvas上的x坐标
        var y = 20 + Math.random() * 8; //文字在canvas上的y坐标
        context.font = "bold 23px 微软雅黑";
        context.translate(x, y);
        context.rotate(deg);
        context.fillStyle = this.randomColor();
        context.fillText(txt, 0, 0);
        context.rotate(-deg);
        context.translate(-x, -y);
      }
      //验证码上显示6条线条
      for (var i = 0; i <= 5; i++) {
        context.strokeStyle = this.randomColor();
        context.beginPath();
        context.moveTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        );
        context.lineTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        );
        context.stroke();
      }
      //验证码上显示31个小点
      for (var i = 0; i <= 30; i++) {
        context.strokeStyle = this.randomColor();
        context.beginPath();
        var x = Math.random() * canvas_width;
        var y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.stroke();
      }

      //最后把取得的验证码数组存起来，方式不唯一
      var num = this.value
      console.log(num, 'num');
      this.true_code = num;
    },
    //得到随机的颜色值
    randomColor() {
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      return "rgb(" + r + "," + g + "," + b + ")";
    },
    //canvas点击刷新
    handleCanvas() {
      this.Huoqucode();
    },
    getLocalStorage() {
      if (localStorage.getItem("saveUser")) {
        let User = JSON.parse(localStorage.getItem("saveUser"));
        //console.log(User);
        this.accountNumber = User.username;
        this.pswd = User.password;
        this.checked = User.checked;
      }
    },
  },
  mounted() {
    this.getLocalStorage();
    this.Huoqucode()
    // var moment = require("moment");
    // // 起始时间
    // let startTime = "2020-07-02 14:40:23"
    // // 结束时间(当前时间)
    // let endTime = moment().format("YYYY-MM-DD HH:mm:ss")
    // // 计算两个时间相差秒数(时间差单位可以是years,months,days,minutes,seconds)
    // let timeDiff = moment(endTime).diff(moment(startTime), "seconds")
    // //console.log(toString(50));
  },
  created() {
    // let endTime=sessionStorage.getItem('endTime') //上次点击获取验证码 60秒结束时间点
    // let nowTime=new Date().getTime()
    // //console.log('现在时间',nowTime);
    // //console.log('倒计时结束时间',endTime);
    // if(nowTime<endTime){
    //   let countdown=endTime - nowTime
    //   //console.log('剩余时间',countdown);
    //   //getVerificationCode(countdown)
    // }

  }

};
</script>

<style lang="scss" scoped>
.box {
  width: 360px;
  background-color: #fff;
  border-radius: 8px;
  padding: 31px 24px 32px;
  display: flex;

  .slot {
    >.remember {
      ::v-deep .el-checkbox__label {
        font-size: 12px;
        color: #262626;
      }
    }

    >.phoneInput {
      height: 40px;
      margin-top: 23px;
      margin-bottom: 16px;

      ::v-deep .el-icon-mobile-phone {
        font-size: 19px;
      }

      ::v-deep .el-input__inner {
        height: 40px;
      }
    }

    >.VerificationCode {
      height: 40px;
      margin-bottom: 19px;

      ::v-deep .el-input__prefix {
        margin-left: 2px;
        line-height: 40px;
      }

      ::v-deep .el-input__inner {
        height: 40px;
      }

      .getCode {
        color: #1890ff;
        font-size: 14px;
        line-height: 40px;
        display: inline-block;
        margin-right: 13px;
        position: relative;
        z-index: 800;
        cursor: pointer;
      }

      .timing {
        color: #1890ff;
        font-size: 14px;
        line-height: 40px;
        margin-right: 13px;
      }

      .icon-yanzhengma {
        font-size: 18px;
      }
    }

    .loginBtn {
      background-color: #1890ff;
      height: 40px;
      width: 313px;
      border-radius: 4px;
      text-align: center;
      line-height: 40px;
      color: #fff;
      font-size: 14px;
      margin-top: 47px;
      cursor: pointer;
    }

    >.account {
      margin-top: 23px;
      height: 40px;

      ::v-deep .el-input__inner {
        height: 40px;
      }
    }

    >.pswd {
      margin-top: 16px;

      ::v-deep .el-input__inner {
        height: 40px;
      }
    }

    >.control {
      width: 100%;
      display: flex;
      margin-top: 19px;
      font-size: 12px;
      align-items: center;
      justify-content: space-between;

      .remember {
        ::v-deep .el-checkbox__label {
          font-size: 12px;
          color: #262626;
        }
      }

      >.forget {
        color: #1890ff;
      }
    }
  }
}

.yanZhenBox {
  margin-top: 16px;

  .prefixIcon {
    // display: flex;
    // align-items: center;
    line-height: 40px;
    width: 25px;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;

    .icon-yanzhengma {
      font-size: 13px;
    }
  }

  .canvasBox {
    height: 40px;
    display: flex;
    align-items: center;

    #canvas {
      width: 92px;
      float: right;
      display: block;
      border: 1px solid #ccc;
      border-radius: 4px;
      height: 36px;
      cursor: pointer;
    }
  }
}
</style>
